package com.youlu.campus.service.course;

import com.youlu.campus.entity.course.entity.CalLeaveDaysEntity;
import com.youlu.campus.service.utils.ZmDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * https://timor.tech/api/holiday
 * @author : [dengbo]
 * @className : CalLeaveDayService
 * @description : [法定日期服务]
 * @createTime : [2022/11/22 21:58]
 */
@Service
@Slf4j
public class CalLeaveDayService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public List<CalLeaveDaysEntity> getCalLeaveDays(Date startTime, Date endTime) {
        QueryWrapper q = new QueryWrapper();
        q.range("dateTime", startTime, endTime);
        List<CalLeaveDaysEntity> list = mongoTemplate.find(q, CalLeaveDaysEntity.class);
        // 查询是否是法定日期
        list = list.stream().filter(CalLeaveDaysEntity::getHoliday).collect(Collectors.toList());
        return list;
    }

    /**
     * 获取工作日天数
     * @param startDate
     * @param endDate
     * @return
     */
    public int getCalLeaveDaysNum(Date startDate,Date endDate){
        Date payZeroDate = ZmDateUtils.getZeroDate(startDate);
        Date localZeroDate = ZmDateUtils.getZeroDate(endDate);
        // 查询法定节假日
        List<CalLeaveDaysEntity> list = getCalLeaveDays(payZeroDate, localZeroDate);
        List<String> dateStrList = list.stream().map(CalLeaveDaysEntity::getDate).collect(Collectors.toList());
        int num = ZmDateUtils.getCalLeaveDays(payZeroDate, localZeroDate, dateStrList);
        return num;
    }


    public boolean isCalLeaveDay(Date date) {
        Instant instant = date.toInstant();
        LocalDate localDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
        QueryWrapper q = new QueryWrapper();
        q.where("dateTime", localDate);
        CalLeaveDaysEntity entity = mongoTemplate.findOne(q, CalLeaveDaysEntity.class);
        return entity == null ? false : entity.getHoliday();
    }

}
